package com.A21MobileSales;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.ActionMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.A21.Adapter.OrderSummary_Adapter;
import com.A21.Object.A21OrderHeader;
import com.A21.Object.Global;
import com.A21.XMLSerialization.XmlSerializer;
import com.A21MobileSales.DataBase.DatabaseHelper;
import com.A21MobileSales.JsonServices.Upload;

public class OrderSummary extends Activity {

	DatabaseHelper ObjDBHelper;
	Calendar myCalendar = Calendar.getInstance();
	ArrayList<A21OrderHeader> lstOrderSummary;
	ImageButton btn_Add;
	ImageButton btn_back;
	private String Code, CName, TrnType;
	ListView lvTrnsaction;
	TextView tv_CName, tv_OrderSummary;
	Spinner spnerTrnOption;
	public ActionMode mActionMode;
	public OrderSummary_Adapter cartAdapter;
	private String CurrentTableHeader = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_summary);
		if (getIntent().hasExtra("Code")) {
			Code = getIntent().getStringExtra("Code");
		}
		if (getIntent().hasExtra("CName")) {
			CName = getIntent().getStringExtra("CName");
		}
		if (getIntent().hasExtra("TrnType")) {
			TrnType = getIntent().getStringExtra("TrnType");
		}
		try {
			btn_Add = (ImageButton) findViewById(R.id.btn_Add);
			tv_CName = (TextView) findViewById(R.id.tv_CName);
			tv_OrderSummary = (TextView) findViewById(R.id.tv_OrderSummary);

			tv_CName.setText(CName);
			if (TrnType.equals("")) {
				btn_Add.setVisibility(View.GONE);
				tv_OrderSummary.setText("ORDER SUMMARY");
			} else if (TrnType.equals("CW")) {
				tv_OrderSummary.setText("SALE ORDER SUMMARY");
			} else if (TrnType.equals("CA")) {
				tv_OrderSummary.setText("CASH INVOICE SUMMARY");
			} else if (TrnType.equals("CR")) {
				tv_OrderSummary.setText("CREDIT INVOICE SUMMARY");
			}
			btn_Add.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Bundle b = new Bundle();
					b.putString("Code", Code);
					b.putString("CName", CName);
					b.putString("TrnType", TrnType);
					b.putString("Id", "0");
					Intent _intent = new Intent();
					_intent.putExtras(b);
					_intent.setClass(OrderSummary.this, OrderTab.class);
					startActivity(_intent);
					OrderSummary.this.finish();
				}
			});

			btn_back = (ImageButton) findViewById(R.id.btn_back);
			btn_back.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					GoBack();
				}
			});
			ObjDBHelper = new DatabaseHelper(this);
			lvTrnsaction = (ListView) findViewById(R.id.Trn_summary_list);

			/*
			 * lvTrnsaction.setOnItemClickListener(new OnItemClickListener() {
			 * 
			 * @Override public void onItemClick(AdapterView<?> Adapter, View v,
			 * int Pos, long Id) { try {
			 * 
			 * Bundle b = new Bundle(); b.putString("Code", Code);
			 * b.putString("CName", CName); b.putString("Id",
			 * String.valueOf(lstOrderSummary.get(Pos).Id));
			 * if(TrnType.equals("")){ b.putString("Screen", "Dashboard"); }
			 * b.putString("TrnType", lstOrderSummary.get(Pos).TrnType); Intent
			 * _intent = new Intent(); _intent.putExtras(b);
			 * _intent.setClass(OrderSummary.this, OrderTab.class);
			 * startActivity(_intent); } catch (Exception ex) {
			 * ex.printStackTrace(); }
			 * 
			 * } });
			 */
			String Screen = "";
			if (TrnType.equals("")) {
				Screen = "Dashboard";
				lstOrderSummary = ObjDBHelper.GetAllOrderSummary();
			} else {
				if (TrnType.equals("CW")) {
					CurrentTableHeader = "A21OPOrderHeader";
				} else if (TrnType.equals("CA")) {
					CurrentTableHeader = "A21OPCashInvoiceHeader";

				} else if (TrnType.equals("CR")) {
					CurrentTableHeader = "A21OPCreditInvoiceHeader";
				}
				lstOrderSummary = ObjDBHelper.GetOrderSummaryByTableCustomer(
						CurrentTableHeader, Code);
			}
			cartAdapter = new OrderSummary_Adapter(OrderSummary.this,
					lstOrderSummary, Screen);
			lvTrnsaction.setAdapter(cartAdapter);
			InitTrnOptionsSpinner();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		GoBack();
	}

	private void GoBack() {
		Bundle b = new Bundle();
		b.putString("Code", Code);
		b.putString("CName", CName);
		b.putString("TrnType", TrnType);
		Intent _intent = new Intent();
		_intent.putExtras(b);
		if (TrnType.equals("")) {
			_intent.setClass(OrderSummary.this, HomeScreen.class);
		} else {
			_intent.setClass(OrderSummary.this, CustomerSelection.class);
		}
		startActivity(_intent);
		this.finish();
	}

	public void ClearSelection() {
		for (A21OrderHeader row : lstOrderSummary) {
			row.IsSelected = false;
		}
		cartAdapter.notifyDataSetChanged();
	}

	public void InitTrnOptionsSpinner() {
		spnerTrnOption = (Spinner) findViewById(R.id.spnerTrnOption);
		if (!TrnType.equals("")) {
			spnerTrnOption.setVisibility(View.GONE);
			return;
		}
		List<String> list = new ArrayList<String>();
		list.add("All");
		list.add("Cash Sales");
		list.add("Credit Sales");
		list.add("Sales Order");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnerTrnOption.setAdapter(dataAdapter);
		spnerTrnOption.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> Adater, View v, int Pos,
					long ID) {
				String selItem = spnerTrnOption.getSelectedItem().toString();
				if (selItem.equals("All")) {
					lstOrderSummary = ObjDBHelper.GetAllOrderSummary();
				} else {
					if (selItem.equals("Cash Sales")) {
						CurrentTableHeader = "A21OPCashInvoiceHeader";
					} else if (selItem.equals("Credit Sales")) {
						CurrentTableHeader = "A21OPCreditInvoiceHeader";
					} else if (selItem.equals("Sales Order")) {
						CurrentTableHeader = "A21OPOrderHeader";
					}
					lstOrderSummary = ObjDBHelper
							.GetOrderSummaryByTable(CurrentTableHeader);
				}
				cartAdapter = new OrderSummary_Adapter(OrderSummary.this,
						lstOrderSummary, "Dashboard");
				lvTrnsaction.setAdapter(cartAdapter);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		spnerTrnOption.setSelection(0);

	}

	public void DeleteSelection() {
		Iterator<A21OrderHeader> lst = lstOrderSummary.iterator();
		while (lst.hasNext()) {
			A21OrderHeader row = lst.next();
			if (row.IsSelected) {
				if (row.Id > 0) {
					ObjDBHelper = new DatabaseHelper(this);
					if (row.TrnType.equals("CW")) {
						CurrentTableHeader = "A21OPOrderHeader";
					} else if (row.TrnType.equals("CA")) {
						CurrentTableHeader = "A21OPCashInvoiceHeader";

					} else if (row.TrnType.equals("CR")) {
						CurrentTableHeader = "A21OPCreditInvoiceHeader";
					}
					ObjDBHelper.DeleteRowByTableId(CurrentTableHeader,
							String.valueOf(row.Id));
				}
				lst.remove();
			}
		}
		cartAdapter.notifyDataSetChanged();
		mActionMode.finish();
	}

	public void UploadSelection() {
		new btnSyncTask().execute();
	}

	// Sync All Details from server.
	private class btnSyncTask extends AsyncTask<String, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(OrderSummary.this);
		String StrMsg = null;

		protected void onPreExecute() {
			this.dialog.setMessage("Loading...");
			this.dialog.setCanceledOnTouchOutside(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... a) {
			try {

				String strUserName = Global.getLoggedInUser().User;
				String strPassword = Global.getLoggedInUser().strPassword;
				Upload ObjUL = new Upload(OrderSummary.this, strUserName,
						strPassword);
				String StrXml = "";
				Iterator<A21OrderHeader> lst = lstOrderSummary.iterator();
				while (lst.hasNext()) {
					A21OrderHeader row = lst.next();
					if (row.IsSelected) {
						XmlSerializer ObjSerialize = new XmlSerializer();
						TelephonyManager telephonyManager = (TelephonyManager) OrderSummary.this
								.getSystemService(Context.TELEPHONY_SERVICE);
						String IMEI_Number = telephonyManager.getDeviceId();
						if (IMEI_Number == null) {
							IMEI_Number = Build.SERIAL;
						}
						row.IMEIID = IMEI_Number;
						String currentTableDetail = "";
						if (row.TrnType.equals("CW")) {
							currentTableDetail = "A21OPOrderDetail";
						} else if (TrnType.equals("CA")) {
							currentTableDetail = "A21OPCashInvoiceDetail";
						} else if (TrnType.equals("CR")) {
							currentTableDetail = "A21OPCreditInvoiceDetail";
						}
						row.TrnDetails = ObjDBHelper.GetOrderDetailByHeaderId(
								currentTableDetail, String.valueOf(row.Id));
						if (row.TrnDetails.size() == 0) {
							continue;
						}
						ArrayList<A21OrderHeader> lstH = new ArrayList<A21OrderHeader>();
						lstH.add(row);
						StrXml = ObjSerialize.objectToXml(lstH);
						ObjUL.PostTransaction(StrXml);
						lst.remove();
					}
				}

				StrMsg = "Success";
			} catch (Exception ex) {
				StrMsg = ex.getMessage();
			}

			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final Void unused) {

			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				this.dialog = null;
			}
			try {
				if (StrMsg != null) {
					if (StrMsg.equals("Success")) {
						cartAdapter.notifyDataSetChanged();
						mActionMode.finish();
						Toast.makeText(OrderSummary.this,
								"Transaction has been posted successfully!",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(OrderSummary.this, StrMsg,
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(OrderSummary.this,
							"Please check the network connection!!!",
							Toast.LENGTH_SHORT).show();
				}

			} catch (Exception ex) {

				ex.printStackTrace();

			}

		}
	}

	public StringBuilder GetStringBuilderDate() {
		// Generate Order Date.
		final Calendar c = Calendar.getInstance();
		int yy = c.get(Calendar.YEAR);
		int mm = c.get(Calendar.MONTH);
		int dd = c.get(Calendar.DAY_OF_MONTH);
		int hh = c.get(Calendar.HOUR_OF_DAY);
		int Minute = c.get(Calendar.MINUTE);

		StringBuilder strbuilderTime = new StringBuilder().append(hh)
				.append(":").append(Minute).append(":").append("00");

		return strbuilderTime;
	}

}
